<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_nickname;
	private $_id;
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		/*
		$users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		 */
		$email=$this->username;
		if(preg_match('/([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/',$email))
		{
			$user = User::model() -> find('account=:account',array(':account' => $email));
		}
		elseif(preg_match("/^(13|15|18)\d{9}$/",$email))
		{
			$user = User::model() -> find('account=:account',array(':account' => $email));
		}
		else
		{
			$user = User::model() -> find('nickname=:nickname',array(':nickname' => $email));
		}
		if(empty($user))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($user->md5pwd!==md5($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
		{
			$this->errorCode=self::ERROR_NONE;
			$this->_nickname=$user->nickname;
			$this->_id=$user->id;
		}
		return $this->errorCode==self::ERROR_NONE;
	}

	public function getID()
	{
		return $this->_id;
	}

	public function getName()
	{
		return $this->_nickname;
	}
}
